<template>
  <div class="subject-information-summary-wrapper">
    <!-- 上层 -->
    <div class="top_part">
      <!-- 左边 -->
      <div class="top_left_part">
        <div class="totalNumber">
          <img class="imgClass" src="@/assets/img/user5.png" alt="" />
          <div>
            <div class="title" style="color: #1296db">受试者总数</div>
            <div class="content">{{ subjectCount }}</div>
          </div>
        </div>
        <div class="chartContainer" ref="chartContainerLeftRef"></div>
      </div>
      <!-- 右边 -->
      <div class="top_right_part">
        <div class="totalNumber">
          <img class="imgClass" src="@/assets/img/user7.png" alt="" />
          <div>
            <div class="title" style="color: #ff9870">质疑数</div>
            <div class="content">{{ queryCount }}</div>
          </div>
        </div>
        <div class="chartContainer" ref="chartContainerRightRef"></div>
      </div>
    </div>
    <!-- 下层 -->
    <div class="bottom_part">
      <div class="search_part">
        <el-form :model="formData" label-width="100px">
          <el-row>
            <el-col :span="10">
              <el-form-item label="中心名称：">
                <el-select
                  v-model="formData.coreIds"
                  style="width: 90%"
                  size="mini"
                  multiple
                  placeholder="请选择中心"
                  clearable
                >
                  <el-option
                    v-for="item in coreOfficialOptions"
                    :key="item.coreId"
                    :label="item.coreName"
                    :value="item.coreId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="受试者代码：">
                <el-input
                  v-model="formData.subjectCode"
                  style="width: 100%"
                  size="mini"
                  placeholder="请输入受试者代码"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="受试者状态：">
                <el-select
                  v-model="formData.subState"
                  style="width: 90%"
                  size="mini"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option
                    v-for="item in subStateOptions"
                    :key="item.codeValue"
                    :label="item.statusName"
                    :value="item.codeValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :span="24">
            <el-col :span="24" style="width: 100%; text-align: center">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch()">查询</el-button>
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="handleReset()">重置</el-button>
                <!-- <el-button type="primary" icon="el-icon-upload" size="mini" @click="handleImportData()">导入项目数据集</el-button> -->
                <el-upload
                  action
                  style="margin-left: 8px; display: inline-block;"
                  :http-request="handleImportData"
                  :file-list="fileList"
                  :show-file-list="false"
                >
                  <el-button type="primary" size="mini" icon="el-icon-upload" :loading="importLoading">导入项目数据集</el-button>
                </el-upload>
                <el-button type="danger" style="margin-left: 8px;" icon="el-icon-delete" size="mini" @click="handleImportDeleteData()">清空本项目数据集</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table_part">
        <el-table :data="tableData" v-loading="loading" :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" stripe @cell-click="handleJumpToSubjectDetails">
          <el-table-column label="序号" align="center" type="index"></el-table-column>
          <el-table-column label="受试者代码" align="center" prop="subjectCode">
            <template slot-scope="scope">
              <span @click="handleJumpToSubjectDetails(scope.row)" class="table-column-text active-color">{{
                scope.row.subjectCode
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="受试者状态" align="center" prop="subjectStateName"></el-table-column>
          <el-table-column label="eCRF版本号" align="center" prop="crfVersionNum"></el-table-column>
          <el-table-column label="未录入" align="center" prop="noEnter"></el-table-column>
          <el-table-column label="未提交" align="center" prop="noSubmit"></el-table-column>
          <el-table-column label="未签名" align="center" prop="noSign"></el-table-column>
          <el-table-column label="质疑未回复" align="center" prop="noResponse"></el-table-column>
          <el-table-column label="质疑已回复" align="center" prop="replied"></el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 12px">
          <el-pagination
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="pageParams.pageNo"
            :page-sizes="[10, 20, 50]"
            :page-size="pageParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { debounce } from 'lodash'
import { computed } from 'vue'
import { mapActions, mapMutations } from 'vuex'
export default {
  data() {
    return {
      // 左图表
      chartLeft: '',
      // 左图表配置
      optionsLeft: {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          top: '5%',
          left: 'center',
        },
        series: [
          {
            type: 'pie',
            radius: ['60%', '40%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 18,
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { name: '筛选中(0)', value: 0 },
              { name: '筛选失败(0)', value: 0 },
              { name: '已入组(0)', value: 0 },
              { name: '治疗结束(0)', value: 0 },
            ],
          },
        ],
      },
      // 右图表
      chartRight: '',
      // 右图表配置
      optionsRight: {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          top: '5%',
          left: 'center',
        },
        series: [
          {
            type: 'pie',
            radius: ['60%', '40%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 18,
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: 0, name: '未回复(0)' },
              { value: 0, name: '已回复(0)' },
              { value: 0, name: '已关闭(0)' },
            ],
          },
        ],
      },
      total: null,
      pageParams: {
        pageSize: 10,
        pageNo: 1,
      },
      formData: {
        coreIds: [],
        subjectCode: '',
        subState: '',
      },
      defaultFormData: {
        coreIds: [],
        subjectCode: '',
        subState: '',
      },
      coreOfficialOptions: computed(() => {
        return JSON.parse(localStorage.getItem('coreOfficialOptions'))
      }),
      tableData: [],
      queryCount: '',
      subjectCount: '',
      projectId: '',
      environment: '',
      roleId: '',
      subStateOptions: [],
      fileList: [],
      importLoading: false,
      loading: false
    }
  },

  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.formData.coreIds = JSON.parse(localStorage.getItem('coreIds'))
    this.roleId = localStorage.getItem('roleId')
    this.environment = localStorage.getItem('environment')
    this.getTableData()
    this.getSubjectStateOptionsData()
  },
  mounted() {
    this.chartRight = echarts.init(this.$refs.chartContainerRightRef)
    this.chartRight.setOption(this.optionsRight)
    this.chartLeft = echarts.init(this.$refs.chartContainerLeftRef)
    this.chartLeft.setOption(this.optionsLeft)
    this.getChartData()
  },
  methods: {
    ...mapActions('subjectInformation', ['getSubjectTotalAPI', 'getSubjectSummaryCountAPI', 'importProjectData', 'deleteProjectData']),
    ...mapActions('subjectStatus', ['qryProjectSubjectStatusList']),
    ...mapMutations({
      clear: 'treatment/clear',
    }),

    // 获取受试者状态
    async getSubjectStateOptionsData() {
      const params = {
        projectId: this.projectId,
      }
      const res = await this.qryProjectSubjectStatusList({ params })
      this.subStateOptions = res.data || []
    },

    // 进入受试者详情页面
    handleJumpToSubjectDetails(row) {
      this.clear()
      this.$router.push({
        path: '/ecrf-detail',
        query: {
          id: row.id,
        },
      })
    },

    // 导入项目数据集
    handleImportDeleteData() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: localStorage.getItem('project-database-Id')
      }
      this.deleteProjectData({ params }).then((res) => {
        const { code } = res
        if (code === 200) {
          this.handleReset()
          this.getSubjectStateOptionsData()
          this.$message.success('删除成功!')
        }

      })
    },

    // 改变页码
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getTableData()
    },
    // 改变页码尺寸
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getTableData()
    },
    resizeChart() {
      this.chartLeft.resize()
      this.chartRight.resize()
    },
    // 获取表格数据
    async getTableData() {
      const data = {
        ...this.formData,
        ...this.pageParams,
        projectId: this.projectId,
        environment: this.environment,
        roleId: this.roleId,
      }
      this.loading = true
      const res = await this.getSubjectTotalAPI({ data })
      this.loading = false
      if (res&&res.code === 200) {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }
    },
    // 获取图表数据
    async getChartData() {
      const data = {
        projectId: this.projectId,
        coreIds: this.formData.coreIds,
        roleId: this.roleId,
      }
      const res = await this.getSubjectSummaryCountAPI({ data })
      if (res&&res.code === 200) {
        // 实现自适应
        window.addEventListener('resize', debounce(this.resizeChart, 500))
        if (res.data.records) {
          return
        }
        // 设置右边图表
        const arrQuery = [
          { value: res.data.noResponseQuery, name: `未回复(${res.data.noResponseQuery})` },
          { value: res.data.repliedQuery, name: `已回复(${res.data.repliedQuery})` },
          { value: res.data.closeQuery, name: `已关闭(${res.data.closeQuery})` },
        ]
        this.optionsRight.series[0].data = arrQuery
        this.chartRight.setOption(this.optionsRight)
        this.queryCount = res.data.queryCount
        // 设置左边图表
        const arrSubject = []
        const statusList = res.data.subjectStatus || []
        statusList.forEach(item => {
          arrSubject.push({
            name: `${item.title}(${item.count})`,
            value: item.count,
          })
        })
        this.optionsLeft.series[0].data = arrSubject
        this.chartLeft.setOption(this.optionsLeft)
        this.subjectCount = res.data.subjectCount
      }
    },
    // 点击搜索
    handleSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getTableData()
      this.getChartData()
    },
    // 点击重置
    handleReset() {
      this.formData = {
        ...this.defaultFormData,
      }
      this.handleSearch()
    },

    // 导入项目数据集
    handleImportData(file) {
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('projectId', this.projectId)
      formData.append('projectDatabaseId', localStorage.getItem('project-database-Id'))

      this.importProjectData({ data: formData })
        .then(res => {
          this.importLoading = false
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '导入成功' + res.message,
            })
            this.fileList.push({ name: file.file.name, url: res.data })
            // this.handleSearch()
            // location.reload()
            this.handleReset()
          } else {
            this.$message({
              type: 'error',
              message: '导入数据失败，请稍后重试~',
            })
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    }
  },
}
</script>

<style lang="scss" scoped>
.subject-information-summary-wrapper {
  background-color: $white;
  height: 100%;
  .top_part {
    padding: 12px 12px 0;
    display: flex;
    .top_left_part {
      flex: 1;
      height: 300px;
      display: flex;
      align-items: center;
      &::after {
        content: '';
        display: block;
        width: 10px;
        height: 80%;
        margin-left: auto;
        border-right: 1px solid #999999;
      }
    }
    .top_right_part {
      flex: 1;
      height: 300px;
      display: flex;
      align-items: center;
    }
    .totalNumber {
      flex: 50%;
      display: flex;
      align-content: center;
      justify-content: center;
      .imgClass {
        border-radius: 50%;
        width: 88px;
        height: 88px;
      }
      .title {
        font-weight: bold;
        padding-top: 8px;
        padding-bottom: 4px;
        font-size: 14px;
      }
      .content {
        font-size: 20px;
        padding-left: 6px;
        color: #303133;
      }
    }
    .chartContainer {
      flex: 50%;
      height: 100%;
    }
  }
  .bottom_part {
    padding: 0 12px 12px;
    margin-top: 24px;
    background-color: $white;
  }
  .table-column-text {
    display: inline-block;
    width: 70px;
    cursor: pointer;
  }
  .active-color {
    color: rgb(117, 60, 202);
  }
}
</style>
